import bpy
import bmesh
from bpy.types import Operator
from mathutils import Matrix, Vector


class Draw_Hexagon_Op(Operator):
    bl_idname = "object.draw_hexageon"
    bl_label = "draw hexageon"
    bl_description = "draw a hexageon"

    # def execute(self,context):

    #     # Each element of the array is a tuple containing
    #     # an x, y and z component.
    #     verts = [
    #         (0.0, 0.5, 0.0),
    #         (-0.433013, 0.25, 0.0),
    #         (-0.433013, -0.25, 0.0),
    #         (0.0, -0.5, 0.0),
    #         (0.433013, -0.25, 0.0),
    #         (0.433013, 0.25, 0.0)]

    #     # Each face is a tuple that contains the indices
    #     # that point to elements in the array above. An
    #     # n-gon will only have one tuple, but for each
    #     # additional face, add another tuple.
    #     faces = [(0, 1, 2, 3, 4, 5)]

    #     # If the faces list above is specified, then
    #     # the edges list needs only to be an empty list,
    #     # i.e. [] .
    #     edges = [
    #         (0, 1),
    #         (1, 2),
    #         (2, 3),
    #         (3, 4),
    #         (4, 5),
    #         (5, 0)]

    #     # Create mesh from above data.
    #     mesh_name = "Hexagon"
    #     mesh_data = bpy.data.meshes.new(mesh_name)
    #     mesh_data.from_pydata(verts, edges, faces)

    #     # Returns True if any invalid geometry was removed.
    #     corrections = mesh_data.validate(
    #     verbose=True,
    #     clean_customdata=True)

    #     # Load BMesh with mesh data.
    #     bm = bmesh.new()
    #     bm.from_mesh(mesh_data)

    #     bm.to_mesh(mesh_data)
    #     bm.free()
    #     mesh_obj = bpy.data.objects.new(mesh_data.name, mesh_data)
    #     bpy.context.collection.objects.link(mesh_obj)

    #     return {'FINISHED'}

    def execute(self, context):
        D = bpy.data
        C = bpy.context

        # Wrap vert tuples in a Vector constructor.
        verts = [
            Vector((0.0, 0.5, 0.0)),
            Vector((-0.433013, 0.25, 0.0)),
            Vector((-0.433013, -0.25, 0.0)),
            Vector((0.0, -0.5, 0.0)),
            Vector((0.433013, -0.25, 0.0)),
            Vector((0.433013, 0.25, 0.0))]
        faces = [(0, 1, 2, 3, 4, 5)]

        # Apply transform to each vertex coordinate.
        transform = Matrix.Shear('XZ', 4, (0.375, -0.125))
        for i in range(0, len(verts)):
            verts[i] = transform @ verts[i]

        mesh_data = D.meshes.new("Hexagon")
        mesh_data.from_pydata(verts, [], faces)
        mesh_data.validate()
        bm = bmesh.new()
        bm.from_mesh(mesh_data)
        bm.to_mesh(mesh_data)
        bm.free()
        mesh_obj = D.objects.new(mesh_data.name, mesh_data)
        C.collection.objects.link(mesh_obj)

        return {'FINISHED'}
